from typing import List, Optional
from models.item import Item
from datetime import datetime

class ItemRepository:
    """商品数据访问层"""
    
    def __init__(self):
        self._items: List[Item] = []
        self._next_id = 1
        self._initialize_demo_data()
    
    def _initialize_demo_data(self):
        """初始化演示数据"""
        demo_items = [
            {"name": "苹果", "description": "新鲜的红苹果", "price": 5.0, "category": "水果"},
            {"name": "香蕉", "description": "优质香蕉", "price": 3.0, "category": "水果"},
            {"name": "笔记本电脑", "description": "高性能笔记本电脑", "price": 8000.0, "category": "电子产品"},
            {"name": "咖啡", "description": "现磨咖啡豆", "price": 25.0, "category": "饮品"},
        ]
        
        for item_data in demo_items:
            item = Item(
                id=self._next_id,
                **item_data,
                created_at=datetime.now(),
                updated_at=datetime.now()
            )
            self._items.append(item)
            self._next_id += 1
    
    def get_all(self, skip: int = 0, limit: int = 100) -> List[Item]:
        """获取所有商品"""
        return self._items[skip: skip + limit]
    
    def get_by_id(self, item_id: int) -> Optional[Item]:
        """根据ID获取商品"""
        for item in self._items:
            if item.id == item_id:
                return item
        return None
    
    def get_by_category(self, category: str) -> List[Item]:
        """根据分类获取商品"""
        return [item for item in self._items if item.category == category]
    
    def get_categories(self) -> List[str]:
        """获取所有分类"""
        return list(set(item.category for item in self._items))
    
    def create(self, item_data: dict) -> Item:
        """创建新商品"""
        item = Item(
            id=self._next_id,
            **item_data,
            created_at=datetime.now(),
            updated_at=datetime.now()
        )
        self._items.append(item)
        self._next_id += 1
        return item
    
    def update(self, item_id: int, update_data: dict) -> Optional[Item]:
        """更新商品"""
        item = self.get_by_id(item_id)
        if item:
            item.update(**update_data)
            return item
        return None
    
    def delete(self, item_id: int) -> Optional[Item]:
        """删除商品"""
        for i, item in enumerate(self._items):
            if item.id == item_id:
                return self._items.pop(i)
        return None
    
    def count(self) -> int:
        """获取商品总数"""
        return len(self._items)
    
    def exists(self, item_id: int) -> bool:
        """检查商品是否存在"""
        return self.get_by_id(item_id) is not None
    
    def demo_repository_operations(self) -> dict:
        """Demo: 演示Repository层直接操作Models"""
        
        # Repository层只处理Models，不知道Schemas存在
        demo_data = {
            "name": "Repository层Demo商品",
            "description": "Repository层只处理Models对象",
            "price": 66.66,
            "category": "Repository Demo"
        }
        
        # 1. 创建Model (Repository层职责)
        created_item = self.create(demo_data)
        
        # 2. 查询Model
        found_item = self.get_by_id(created_item.id)
        
        # 3. 更新Model
        update_data = {"price": 99.99}
        updated_item = self.update(created_item.id, update_data)
        
        return {
            "repository_layer_demo": "Repository层只处理Models",
            "核心原则": "Repository层完全不知道Schemas存在",
            "数据格式": {
                "输入": "Dict (从Service层传入)",
                "处理": "Models对象操作",
                "存储": "内存数据库 self._items",
                "输出": "Models对象"
            },
            "operations": {
                "created_model": created_item.to_dict(),
                "found_model": found_item.to_dict() if found_item else None,
                "updated_model": updated_item.to_dict() if updated_item else None
            },
            "memory_database_count": len(self._items)
        } 